<?php

namespace app\admin\service;

use app\store\model\Store;
use think\facade\Db;

class StoreService
{
    public function getStoreList()
    {
        $model = new Store();
        $stores = $model->field('id,store_name,store_logo,company_name,legal_person,legal_phone,status,create_time,update_time')->paginate(10);

        return $stores;
    }

    public function findStore($id)
    {   
        $store = Db::name('store')
                    ->field('a.id,a.store_name,a.store_logo,a.company_name,a.business_license,a.id_number,a.id_card_front,a.id_card_reverse,
                    a.legal_person,a.legal_phone,a.company_address,a.status,b.username')
                    ->alias('a')
                    ->join('admin b','a.id=b.store_id')
                    ->where('b.is_supper',1)
                    ->find();

        return $store;
    }

    public function saveStore($data)
    {   
        
        $store = Store::create($data);
        $data['is_supper'] = 1;
        $user = $store->admin()->save($data);

        Db::name('admin_role')->insert(['admin_id' => $user['id'],'role_id' => 1]);

        Db::name('user_grade')->insert([
            'store_id' => $store['id'],
            'grade_name' => '普通会员',
            'status' => 1,
            'is_default' => 1,
        ]);

        return $store['id'];
    }

    public function updateStore($data)
    {   
        $store = Store::update($data);

        if(!empty($data['password'])){
            Db::name('admin')
            ->where(['store_id' => $store['id'], 'is_supper' => 1])
            ->update(['password' => password_hash($data['password'],PASSWORD_DEFAULT)]);
        }

        return $store['id'];
    }
}
